package com.beetobe.callib.event;

import java.io.IOException;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.TimeZone;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;

import com.beetobe.callib.CalendarLibHelper;
import com.beetobe.callib.CalendarLibHelper.SelectDay;
import com.beetobe.main.schedule.CalendarActivity;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.services.calendar.model.Events;

public class AsyncInsertEvent extends AsyncTask<Void, Void, Void> {

	private Activity activity;
	private ProgressDialog dialog;
	private String AccName;
	private final String calendarId;
	private com.google.api.services.calendar.Calendar client;

	private int WHERE_FROM = 0;

	private int FROM_ADDFRIEND = 3;

	private int FROM_LOAD = 2;

	private int FROM_INSERT = 1;

	private int insertType;

	public AsyncInsertEvent(Activity activity, String calendarId, int insertType) {
		this.activity = activity;
		client = CalendarLibHelper.client;
		this.calendarId = calendarId;
		dialog = new ProgressDialog(activity);
		this.insertType = insertType;
	}

	public AsyncInsertEvent(String calendarId, String AccName, int insertType) {
		client = CalendarLibHelper.client;
		this.calendarId = calendarId;
		this.AccName = AccName;
		this.insertType = insertType;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// dialog.setMessage("Inserting event...");
		// dialog.show();
	}

	@Override
	protected Void doInBackground(Void... arg0) {
		try {

			// event.setSummary(CalendarLibHelper.newCalendarName); // 占쌈쏙옙

			// 占싣뤄옙 占쌘듸옙占�占쏙옙占쏙옙 占쏙옙占쏙옙占쏙옙占�email占쏙옙 占쏙옙청占쏙옙占쏙옙 占쏙옙占쏙옙占쏙옙 占쌘듸옙
			// ArrayList<EventAttendee> attendees = new
			// ArrayList<EventAttendee>();
			// attendees.add(new
			// EventAttendee().setEmail("sudogo00@gmail.com"));
			// event.setAttendees(attendees);

			// 占싱븝옙트 占쏙옙占쌜시곤옙 占쏙옙占쏙옙
			// Date startDate = new Date();
			// DateTime start = new
			// DateTime(startDate,TimeZone.getTimeZone("UTC"));
			// event.setStart(new EventDateTime().setDateTime(start));

			// 占싱븝옙트 占쏙옙占쏙옙챨占�占쏙옙占쏙옙
			// Date endDate = new Date(startDate.getTime() + 3600000); // 占쏙옙占쏙옙
			// 占시곤옙
			// + 3600占쏙옙(1占시곤옙)
			// DateTime end = new DateTime(endDate,
			// TimeZone.getTimeZone("UTC"));
			// event.setEnd(new EventDateTime().setDateTime(end));
			if (insertType == FROM_ADDFRIEND) {

				Time now = new Time();
				now.setToNow();

				com.google.api.services.calendar.model.Calendar calendar = client
						.calendars().get(calendarId).execute();

				Events events = client.events().list(calendar.getId())
						.setTimeMin(getEventTime(-3))
						.setTimeMax(getEventTime(3)).execute();

				for (Event event : events.getItems()) {
					EventInfo info = new EventInfo(event.getId(),
							event.getSummary());

					StringTokenizer tokenizer = new StringTokenizer(
							info.toString(), "ㅫ");
					String date = tokenizer.nextToken();
					String content = tokenizer.nextToken();

					StringTokenizer dateToken = new StringTokenizer(date, ".");
					int year = Integer.parseInt(dateToken.nextToken());
					int month = Integer.parseInt(dateToken.nextToken());
					int day = Integer.parseInt(dateToken.nextToken());

					if (content.equals("[OwnerID]"
							+ CalendarLibHelper.accountName)) {
						Event inevent = new Event();
						inevent.setStart(new EventDateTime()
								.setDateTime(getStartEventTime(year,
										(month - 1), (day - 1))));
						inevent.setEnd(new EventDateTime()
								.setDateTime(getEndEventTime(year, (month - 1),
										(day - 1))));
						inevent.setSummary(now.year + "." + (now.month + 1)
								+ "." + now.monthDay + "ㅫ" + "[ClientID]"
								+ AccName);

						Event createdEvent = client.events()
								.insert(calendarId, inevent).execute();

						EventInfo Info = new EventInfo(createdEvent.getId(),
								createdEvent.getSummary());
						CalendarLibHelper.eventList.add(Info);
						break;

					}

				}
			} else {
				Event event = new Event();
				if (insertType == FROM_INSERT) {
					Time now = new Time();
					now.setToNow();

					event.setStart(new EventDateTime()
							.setDateTime(getStartEventTime(now.year, now.month,
									now.monthDay - 2)));
					event.setEnd(new EventDateTime()
							.setDateTime(getEndEventTime(now.year, now.month,
									now.monthDay - 2)));
					event.setSummary(now.year + "." + (now.month + 1) + "."
							+ (now.monthDay - 1) + "ㅫ" + "[OwnerID]"
							+ CalendarLibHelper.accountName);
					Event createdEvent = client.events()
							.insert(calendarId, event).execute();

					EventInfo info = new EventInfo(createdEvent.getId(),
							createdEvent.getSummary());
					CalendarLibHelper.eventList.add(info);
				}
				for (int i = 0; i < CalendarLibHelper.selectDay.size(); i++) {
					SelectDay day = CalendarLibHelper.selectDay.get(i);

					event.setStart(new EventDateTime()
							.setDateTime(getStartEventTime(day.getYear(),
									day.getMonth() - 1, day.getDay() - 1)));
					event.setEnd(new EventDateTime()
							.setDateTime(getEndEventTime(day.getYear(),
									day.getMonth() - 1, day.getDay() - 1)));
					if (insertType == FROM_INSERT) {
						event.setSummary(day.getYear() + "." + day.getMonth()
								+ "." + day.getDay() + "ㅫ" + "[Host]Create");
					} else if (insertType == FROM_LOAD) {
						event.setSummary(day.getYear() + "." + day.getMonth()
								+ "." + day.getDay() + "ㅫ" + "[GUEST]"
								+ CalendarLibHelper.accountName);
					}
					// Log.w("Summary : ", event.getSummary());
					// Log.w("End   Day : ", getStartEventTime(day.getDay()) +
					// "");

					// 占싱븝옙트 占쏙옙
					Event createdEvent = client.events()
							.insert(calendarId, event).execute();

					EventInfo info = new EventInfo(createdEvent.getId(),
							createdEvent.getSummary());
					CalendarLibHelper.eventList.add(info);

				}
			}
		} catch (IOException e) {
			// activity.handleGoogleException(e);
		} catch (NullPointerException e) {
			Log.w("AsyncInsertEvent ", "에러");
			Log.w("TAG", e.getMessage());
		} finally {
			CalendarLibHelper.isEventInserted = true;
			// CalendarActivity.onRequestCompleted();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		// dialog.dismiss();
		// CalendarActivity.finish();
		// CalendarActivity.refresh();
	}

	private DateTime getEventTime(int period) {
		Time endTime = new Time();
		endTime.setToNow();
		endTime.month += period;
		endTime.normalize(true);
		Date makeDate = new Date(endTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

	private DateTime getStartEventTime(int year, int month, int day) {
		Time makeTime = new Time();
		makeTime.set(-1, -1, 3, day + 1, month, year);
		// 占쏙옙(month)占쏙옙 占쌓댐옙占�占쌍억옙占쌍곤옙, 占쏙옙(monthDay)占쏙옙 +1占쌔쇽옙 占쌍억옙占쏙옙占쏙옙占�
		// makeTime.normalize(true);
		Date makeDate = new Date(makeTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

	private DateTime getEndEventTime(int year, int month, int day) {
		Time makeTime = new Time();
		makeTime.set(-1, -1, 5, day + 1, month, year);
		// 占쏙옙(month)占쏙옙 占쌓댐옙占�占쌍억옙占쌍곤옙, 占쏙옙(monthDay)占쏙옙 +1占쌔쇽옙 占쌍억옙占쏙옙占쏙옙占�
		// makeTime.normalize(true);
		Date makeDate = new Date(makeTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}
}
